package com.fatgirl.components
{
	import com.fatgirl.load.LoadData;
	import com.fatgirl.load.LoadFactory;
	import com.fatgirl.load.loadStrategy.URLLoaderStrategy;
	import com.fatgirl.utils.binding.DataBinding;

	/**
	 * XML 工厂
	 * 预先加载，后获取 
	 * @author iceman
	 * 
	 */
	public class XmlFactory
	{
		private static var s_XmlFactory:XmlFactory;
		private var m_xmlList:Array;
		private var m_url:String;
		private var m_xmlUrlList:Array;
		private var m_completeFun:Function;
		
		private var m_host:String = "";
		public function XmlFactory()
		{
			if(s_XmlFactory) throwError(this,FatError.SINGLETON_CLASS);
			m_xmlList =  new Array;
		}
		public static function getInstance():XmlFactory
		{
			if(!s_XmlFactory)
			{
				s_XmlFactory  = new XmlFactory;
				LoadFactory.getInstance("peizhi").addLoadSuffixStrategy("xml",URLLoaderStrategy);
			}
			return s_XmlFactory;
		}
		/**
		 * 设置 相对地址路径 
		 * @param _str
		 * 
		 */
		public function setHost(_str:String):void
		{
			LoadFactory.getInstance("peizhi").host = _str;
		}
		/**
		 * 设置加载策略类 
		 * @param _class
		 * 
		 */
		public function setLoaderStrategy(_class:Class):void
		{
			LoadFactory.getInstance("peizhi").addLoadSuffixStrategy("xml",_class);
		}
		/**
		 * 此处填写相对路径即可（名字即可），全路径会有相应配置 
		 * @param _url
		 * @return 
		 * 
		 */
		public function getXml(_url:String):XML
		{
			_url = LoadFactory.getInstance("peizhi").host + _url;
			if(m_xmlList[_url]) return m_xmlList[_url];
			else throwError(this,FatError.VALUE_IS_NULL,_url);
			return null;
		}
		/**
		 * 初始化加载数组和回调函数 
		 * @param _arr 加载数组
		 * @param _completeFun 加载完毕回调
		 * 
		 */
		public function init(_arr:Array,_completeFun:Function):void
		{
			m_xmlUrlList = _arr;
			m_completeFun = _completeFun;
			if(!m_xmlUrlList)
			{
				throwError(this,FatError.VALUE_IS_NULL);
				return;
			}
			loadXml();
		}
		/**
		 * 内部回调使用 
		 * @param _obj
		 * 
		 */
		public function goOn(_obj:Object):void
		{
			var t_url:String = LoadFactory.getInstance("peizhi").host+m_url;
			t_url = t_url.split("?")[0];//去掉版本信息
			m_xmlList[t_url] = XML(_obj);
			m_url = null;
			loadXml();
		}
		private function loadXml():void
		{
			if(!m_xmlUrlList.length)
			{
				if(m_completeFun!=null) m_completeFun.call(null);
				return;
			}
			m_url = m_xmlUrlList.pop();
			var t_loadData:LoadData = LoadFactory.getInstance("peizhi").getData(m_url);
			DataBinding.binding(this,"goOn",t_loadData,"data");
		}
	}
}